<?php

class MemberAction extends CommonAction
{
    //判断是否为微信
    public function is_weixin()
    {
        if (strpos($_SERVER['HTTP_USER_AGENT'], 'MicroMessenger') !== false) {
            return true;
        }
        return false;
    }
	
	
	public function display($temp = ''){
		$map  = "site_id = ".__SITEID__." and groupname = '".strtolower(GROUP_NAME)."' and (modelname = '".strtolower(MODULE_NAME)."' or modelname = '*') and (actionname = '".strtolower(ACTION_NAME)."' or actionname = '*')";
		$Systempages = M('Systempages') -> where($map) -> find();
		
		
		
		
		if(IS_AJAX){
			
			$html = '';
			if($Systempages){
				$ModulesDB = D('Modules');
				$this->initView();
				$this->getModulesByID($this->view, $ModulesDB);
				$html .= $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-header.html');
				$html .= $ModulesDB->getListToString($Systempages['page_view_id'],$this->view,false,true);
				$html .= $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-footer.html');
			}else{
				$html = $this->fetch($temp);
			}
			$list = $_GET['list'];
			$empty = 1;
			$statu=$list?1:0; 
			if($this->get('list')){
				$empty = 0;
			}
			$this->initView();
			die(json_encode(array('empty' => $empty,'tbody'=>$html,'dump'=>$_REQUEST,'statu'=>$statu, 'pages' => $this->view->get('pages'))));
		}else{
			if($Systempages){
				$ModulesDB = D('Modules');
				$this->initView(); 
				echo $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-header.html');
				echo $ModulesDB->getListToString($Systempages['page_view_id'],$this->view,false,true);
				echo $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-footer.html');
				echo $this->view -> fetch(TMPL_PATH.'Home/TemplateDefault/Public-mfooter.html');
			}else{
				parent::display($temp);
			}
		} 
		
	}
	
	
    public $userInfo = array();

    public function _initialize()
    {

        parent::_initialize();
		
		
		
		
		
		
		
		
		
        if ($this->_get('openid')) {
            $map['openid'] = $this->_get('openid');
            $memberModel = D('Member');
            $memberModel->checkLogin($map);
            session('memberInfo', $memberModel->userInfo);
        }
        if ($this->is_weixin() && !$this->memberInfo) {
            session('jumpurl',__SELF__);
            if(IS_AJAX){
				$this->error('用户未登录！', U('Public/login'));
			}else{
				redirect(U('Public/login'));
			}
        }

        if (!$this->memberInfo) {
			session('jumpurl',__SELF__);
            if(IS_AJAX){
				$this->error('用户未登录！', U('Public/login'));
			}else{
				redirect(U('Public/login'));
			}
        }
        if ($this->memberInfo['site_id'] != __RELATEID__) {
            session('memberInfo',NULL);
            if(IS_AJAX){
				$this->error('用户未登录！', U('Public/login'));
			}else{
				redirect(U('Public/login'));
			}
        }
		if($this->memberInfo['status'] == 0){
			$this->error('当前用户已经被禁用！');exit;
		}
        $this->userInfo = M('Member')->where(array('id' => $this->memberInfo['id']))->find();
		if($this->siteInfo['VerifyPhone'] > 0 && $this->userInfo['VerifyPhone'] == 0){
			$this->timeout = 5;
			
			
			if(isset($_POST['verify'])){
				$map['tel'] = $this -> _post('tel');
				$map['verifycode'] = $this -> _post('verify');
				$map['id'] = $this->memberInfo['id'];
				$map['VerifyPhone'] = 0;
				$sd['VerifyPhone'] = 1;
				$sd['verifycode'] = '';
				$ret = M('Member') -> where($map) -> data($sd) -> save();
				if($ret){
					$this->success('验证成功');
				}else{
					$this->error('验证错误，请重新输入验证码!');
				}
			}
			
			
			if(isset($_POST['tel'])){
				//发送验证码
				$tel = $this->_post('tel');
				if(M('Member') -> where(array('site_id' => __RELATEID__,'VerifyPhone'=> 1, 'tel' => $tel)) -> find()){
					$this->error('该手机号码已经被使用！');exit;
				}
				
				
				//生成一个验证码
				$data['verifycode'] = rand(123456,999999);
				$data['tel'] = $tel;
				$ret = M('Member') -> where(array('id' => $this->memberInfo['id'])) -> data($data) -> save();
				if($ret !== false){
					if(SMSSend($tel, $data['verifycode'].'　,5')){
						$this->success('发送成功，请注意查收!');exit;
					}else{
						$this->error('发送失败，请稍候重试!');exit;
					}
				}
			}
			echo $this -> fetch('Index:VerifyPhone');exit;
		}
        if (!$this->userInfo) {
            redirect(U('Public/logout'));
        }
        //dump($this->userInfo);
        //认证信息


        $this->assign('userInfo', $this->userInfo);
        $this->assign('username', $this->memberInfo['username']);
        $this->assign('userid', $this->memberInfo['id']);
        //$this->assign('info',$this->userinfo);
    }
	
	
	
    public function head()
    {
        $this->display('Public:head');
    }
	
	
	
	
	
	
	
	//通用文件上传
    public function _upload($file = 'file') {
        import("ORG.Net.UploadFile");
        $upload = new UploadFile(); 
        //设置上传文件大小
        $upload->maxSize = 8*1024*1024;
        $upload->allowExts = explode(',', C('UPLOAD_EXTS'));
        $upload->savePath = "./Public/Uploads/".__SITEID__.'/'. MODULE_NAME . "" . __SITEID__ . "-";
        //自动命名
        $upload->saveRule = 'uniqid';
		
		if($this->_post('rewrite')){
			$upload->saveRule = pathinfo($this->_post('rewrite'),PATHINFO_FILENAME);
	    }
        //创建目录
        $upload->savePath = $upload->savePath . date('Ymd', time()) . "/";
        if (!file_exists("$upload->savePath")) {
            mk_dir($upload->savePath);
        }
        //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb = 1;
        //设置需要生成缩略图的文件后缀
        //$upload->thumbSuffix = "_thumb";
        //设置缩略图最大宽度
        $upload->thumbMaxWidth = $this->thumbMaxWidth;
        //设置缩略图最大高度
        $upload->thumbMaxHeight = $this->thumbMaxHeight;
        $upload->uploadReplace = true;
        if (!$upload->upload()) {
            $error = $upload->getErrorMsg();
            exit($error);
            return false;
        } else {
            $uploadSuccess = true;
            $uploadList = $upload->getUploadFileInfo();
			
            return '/' . trim($uploadList[0]['savepath'], './Public') . '/' . $uploadList[0]['savename'];
        }
    }
	
	
	
	
	
	
	
	
	
    //上传头像
    public function uploadImg()
    {
        $this->name = isset($_POST['name']) ? $_POST['name'] : 'img_url';
            $info = $this->_upload('file');
            //dump($info);exit();
            echo $info;
    }

    //裁剪并保存用户头像
    public function cropImg()
    {
        //图片裁剪数据
        $params = $this->_post();                        //裁剪参数
        if (!isset($params) && empty($params)) {
            return;
        }

        //头像目录地址
        $path = './Public/Uploads/avatar/' . $this->memberInfo['id'] . '/';
        //要保存的图片
        $real_path = $path . $params['picName'];
        //临时图片地址
        $pic_path = $path . $params['picName'];
        import('ORG.ThinkImage.ThinkImage');
        $Think_img = new ThinkImage(THINKIMAGE_GD);
        //裁剪原图
        $Think_img->open($pic_path)->crop($params['w'], $params['h'], $params['x'], $params['y'])->save($real_path);
        //生成缩略图
        $Think_img->open($real_path)->thumb(100, 100, 1)->save($path . $$params['picName'] . '_100.jpg');
        $Think_img->open($real_path)->thumb(60, 60, 1)->save($path . $$params['picName'] . '_60.jpg');
        $Think_img->open($real_path)->thumb(30, 30, 1)->save($path . $$params['picName'] . '_30.jpg');
        $memberDB = M('Member');
        $savedata['img_url'] = '/Uploads/avatar/' . $this->memberInfo['id'] . '/' . $$params['picName'] . '_100.jpg';
        $map['id'] = $this->memberInfo['id'];
        $memberDB->where($map)->data($savedata)->save();

        $this->success('上传头像成功', U('Index/index'));
    }


    public function showimgBox()
    {
        $this->assign('id', $this->_get('id'));
        $this->display('Public:imagesBox');
    }

    public function upload_Img()
    {

        if ($this->_post('imgo')) {
            $imgo_url2 = $this->_post('imgo_url');
            $imgo_url = $_SERVER['DOCUMENT_ROOT'] . $imgo_url2;
            header('Content-type: image/jpeg');
            $source = imagecreatefromjpeg($imgo_url);
            if ($this->_post('imgo') == 'left') {
                $jd = 90;
            }
            if ($this->_post('imgo') == 'right') {
                $jd = -90;
            }

            $rotate = imagerotate($source, $jd, 0);
            ImageJpeg($rotate, $imgo_url);
            echo json_encode($imgo_url2);

            exit;
        }


        $png = $this->_post('png');
        $this->assign('id', $this->_get('id'));
        if (!isset($png)) {
            $this->display('Public:upload_Img');
            exit();
        } else {


            $path2 = '/Public/Uploads/card/' . $this->memberInfo['id'] . '/' . time() . '.jpg';
            $path = $_SERVER['DOCUMENT_ROOT'] . $path2;


            if (!is_dir(pathinfo($path, PATHINFO_DIRNAME) . '/')) {
                mkdir(pathinfo($path, PATHINFO_DIRNAME) . '/', 511, true);
            }

            $this->base64_to_png("" . str_replace('data:image/jpeg;base64,', '', $png), $path);
            $url['img_url'] = $path2;
            //$this->db->where(array('member_id'=>$this->userInfo['id']))->save($url);
            echo "<script>window.parent.uploaded('{$path2}','" . $this->_get('id') . "');</script>";
            $this->display('Public:upload_Img');
        }


    }

    function base64_to_png($inputfile, $outputfile)
    {
        $imageData = $inputfile;
        $file = fopen($outputfile, "w");
        fwrite($file, base64_decode($imageData));
        fclose($file);
    }

    //统计会员
    public function userCount()
    {
        set_time_limit(0);

 

$timek = mktime(0, 0 , 0,date("m"),date("d"),date("Y"))-86400;
        $timej = mktime(23,59,59,date("m"),date("d"),date("Y"))-86400;
        $cashwhere['dateline'] = array(array('gt',$timek),array('lt',$timej));
		
		
		$cashwhere['member_id'] = $this->memberInfo['id'];
		
       echo (float)$this->yesterdayCash=D('Member_account_log')->where($cashwhere)->Sum('changenum');


       // echo D('Member_member')->where(array('member_id' => $this->memberInfo['id'], 'site_id' => __RELATEID__, 'level' => 0, 'deep' => array('elt',3)))->count();
    }

    //生成推广二维码 
    public function createAffQrcode()
    {
		//查找分成配置
		
		
		$qrcodesetting = M('Site') -> where(array('id' => __SITEID__)) -> getField('qrcodesetting');
	
	    $config = unserialize($qrcodesetting);
		
        if ($this->userInfo['level'] == 0 && ($config['createQr']) == 0) {
            //sendWXMsg($this->userInfo['openid'], '当前等级不能生成推广二维码！');
            exit('当前等级不能生成推广二维码！');
        }
		@curlRequest(U('Home/Ajax/createaffqr', array('id' => $this->memberInfo['id']), true, false, true));
		exit('二维码已经发送到微信，请注意查收！');
        //import('ORG.Net.Http');
        //把二维码拉回到本地
        Vendor('Weixin.Weixin');
        $d['token'] = getSysVal('token');
        $d['appid'] = getSysVal('appid');
        $d['appsecret'] = getSysVal('appsecret');
        $this->weixin = new WeixinChat($d);

        $affid = 'aff_' . $this->memberInfo['id'];

        //exit($affid);

        $tiket = $this->weixin->createQrcode($affid, 1);
        $qrocde = 'http://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' . $tiket['ticket'];//exit($qrocde);
        $qrcodelocal = './Public/qrcode/' . $this->memberInfo['id'] . '/';
        //echo "<img src='".$qrocde."' />";
        if (!is_dir($qrcodelocal)) {
            mkdir($qrcodelocal, 511, true);
        }
        //拉取头像到本地
        import("ORG.Util.Image");
        //读取生成配置
		//echo $this->memberInfo['img_url'];
        $config = unserialize($this->siteInfo['qrcodesetting']);
        @curlDownload($qrocde, $qrcodelocal . 'qrcode.jpg');
        @curlDownload($this->memberInfo['img_url'], $qrcodelocal . 'head.jpg');


        //$this->GrabImage($qrocde,$qrcodelocal.'qrcode.jpg');

        //二维码大小
        $qrsize = explode(',', $config['qrsize']);
        Image::thumb($qrcodelocal . 'qrcode.jpg', $qrcodelocal . 'qrcode.jpg', '', $qrsize[0], $qrsize[1], true);
        //头像大小
        $headsize = explode(',', $config['headsize']);
        Image::thumb($qrcodelocal . 'head.jpg', $qrcodelocal . 'head.jpg', '', $headsize[0], $headsize[1], true);

        //头像位置
        $headposition = explode(',', $config['headposition']);
        Image::water('./Public' . $config['qrbackground'], $qrcodelocal . 'head.jpg', $qrcodelocal . 'myqr.jpg', 100, $headposition[0], $headposition[1], false);


        //二维码位置
        $qrposition = explode(',', $config['qrposition']);
        Image::water($qrcodelocal . 'myqr.jpg', $qrcodelocal . 'qrcode.jpg', $qrcodelocal . 'myqr.jpg', 100, $qrposition[0], $qrposition[1], false);

        //Image::buildString('吴俊源', array(0,0,0), $qrcodelocal.'nickname.png', 'png', 0, false);

        Vendor('water.water');
        $markimg = new water($qrcodelocal . 'myqr.jpg');
        //生成姓名

        $markimg->color = $config['nicknamecolor'];
        $markimg->fontSize = $config['nicknamesize'];
        $markimg->fontFile = './Public/MSYHBD.TTC';
        $nicknameposition = explode(',', $config['nicknameposition']);
        $markimg->setMarkPos($nicknameposition[0], $nicknameposition[1]);
        $markimg->appendTextMark($this->memberInfo['nickname']);
        $markimg->write($qrcodelocal . 'myqr.jpg');
        $this->weixin->sendCustomMessage($this->memberInfo['openid'], $qrcodelocal . 'myqr.jpg', 'image');
        //发送信息
        sendWXMsg($this->memberInfo['openid'], $config['sendMsg']);
    }
public function getRegion(){
		$father_id = isset($_POST['fid'])?intval($_POST['fid']):0;
		$db=M('Region');
		$data = $db->where(array('father_id'=>$father_id))->select();
		$str = '<option value="">-请选择-</option>';
		foreach($data as $k => $v){
			$str .= '<option value="'.$v['region_id'].'">'.$v['region_name'].'</option>';
		}
		if(count($data)>0){
			$str = '<select style="width:auto; display:inline; margin-right:8px;" class="form-control" id="select" datatype="*" onchange="sendRegion(this)" name="area[]">'.$str.'</select>';
		}else{
			$str='';
		}
		echo $str;
	}
	
	public function setRegion(){
		$db=M('Region');
		
		$area = explode(',', trim($this->_post('area'),','));
		
		$ret = "";
		foreach($area as $skey => $sid){
			$father_id = $skey == 0 ? 0 : $area[$skey - 1];
			$data = $db->where(array('father_id'=>$father_id))->select();
			$str = '<option value="">-请选择-</option>';
			foreach($data as $k => $v){
				$selectstr = "";
				if($sid == $v['region_id']){
					$selectstr = 'selected="selected"'; 
				}
				$str .= '<option '.$selectstr.' value="'.$v['region_id'].'">'.$v['region_name'].'</option>';
			}
			if(count($data)>0){
				$str = '<select style="width:auto; display:inline; margin-right:8px;" class="form-control" id="select" datatype="*" onchange="sendRegion(this)" name="area[]">'.$str.'</select>';
			}else{
				$str='';
			}
			$ret .= $str;
		}
		
		echo $ret;
		
		
	}
}